package com.atguigu.controller;

import com.atguigu.entity.Admin;
import com.atguigu.entity.HouseBroker;
import com.atguigu.service.AdminService;
import com.atguigu.service.HouseBrokerService;
import org.apache.dubbo.config.annotation.DubboReference;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.ui.ModelMap;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestMapping;

import java.util.List;

@Controller
@RequestMapping("/houseBroker")
public class HouseBrokerController {

    @DubboReference
    private AdminService adminService;
    @DubboReference
    private HouseBrokerService houseBrokerService;

    /*渲染create视图的处理器,
    查出所有admin放入qingqiu
    */
    @RequestMapping("/create")
    public String create(Long houseId, ModelMap map){
        // 查询所有的admin
        List<Admin> adminList=adminService.findAll();
        map.addAttribute("houseId",houseId);
        map.addAttribute("adminList",adminList);
        return "houseBroker/create";
    }

    @RequestMapping("/save")
    public String save(HouseBroker houseBroker){
        // 根据id查询admin
        Admin admin = adminService.getById(houseBroker.getBrokerId());
        houseBroker.setBrokerId(admin.getId());
        houseBroker.setBrokerName(admin.getName());
        houseBroker.setBrokerHeadUrl(admin.getHeadUrl());
        // 保存broker进入数据库
        houseBrokerService.insert(houseBroker);
        // 渲染成功提示页
        return "common/successPage";
    }

    @RequestMapping("/edit/{id}")
    public String edit(@PathVariable("id") Long id,ModelMap modelMap){
        // 查出当前的houseBroker
        HouseBroker houseBroker = houseBrokerService.getById(id);
        // 获取全部的Admin
        List<Admin> adminList = adminService.findAll();
        modelMap.addAttribute("houseBroker",houseBroker);
        modelMap.addAttribute("adminList",adminList);
        return "houseBroker/edit";
    }
    @RequestMapping("/update")
    public String update(HouseBroker houseBroker){
        Admin admin = adminService.getById(houseBroker.getBrokerId());
        houseBroker.setBrokerName(admin.getName());
        houseBroker.setBrokerHeadUrl(admin.getHeadUrl());
        houseBrokerService.update(houseBroker);
        return "common/successPage";
    }

    @RequestMapping("/delete/{houseId}/{id}")
    public String delete(@PathVariable("houseId")Long houseId,@PathVariable("id")Long id){
        // 调用服务层方法删除经纪人
        houseBrokerService.delete(id);
        // 重新渲染详情页
        return "redirect:/house/"+houseId;

    }

}
